<template>
  <div class="stock-history">
    <h2>股票历史数据</h2>
    <div class="controls">
      <div class="form-group">
        <label for="symbol">股票代码:</label>
        <input 
          id="symbol" 
          v-model="selectedSymbol" 
          type="text" 
          placeholder="请输入股票代码"
          @keyup.enter="fetchHistoryData"
        />
      </div>
      <div class="form-group">
        <label for="limit">数据条数:</label>
        <select id="limit" v-model="limit">
          <option value="30">30条</option>
          <option value="60">60条</option>
          <option value="100">100条</option>
          <option value="200">200条</option>
        </select>
      </div>
      <button @click="fetchHistoryData" :disabled="loading">获取历史数据</button>
      <button @click="updateHistoryData" :disabled="loading">更新历史数据</button>
    </div>

    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">{{ error }}</div>
    <div v-else-if="historyData.length > 0">
      <div class="chart-container">
        <canvas ref="chartCanvas" width="800" height="400"></canvas>
      </div>
      
      <div class="data-table">
        <h3>历史数据详情</h3>
        <div class="table-wrapper">
          <table>
            <thead>
              <tr>
                <th>日期</th>
                <th>开盘价</th>
                <th>最高价</th>
                <th>最低价</th>
                <th>收盘价</th>
                <th>成交量</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in historyData" :key="index">
                <td>{{ formatDate(item.date) }}</td>
                <td>¥{{ item.open.toFixed(2) }}</td>
                <td>¥{{ item.high.toFixed(2) }}</td>
                <td>¥{{ item.low.toFixed(2) }}</td>
                <td>¥{{ item.close.toFixed(2) }}</td>
                <td>{{ item.volume.toLocaleString() }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <div v-else>
      <p>请输入股票代码并点击"获取历史数据"按钮来查看历史数据。</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import apiService from '../services/ApiService';
import {
  Chart,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  LineController,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js';

// 注册Chart.js组件
Chart.register(CategoryScale, LinearScale, PointElement, LineElement, LineController, Title, Tooltip, Legend, Filler);

const selectedSymbol = ref('000001');
const limit = ref(100);
const historyData = ref([]);
const loading = ref(false);
const error = ref(null);
const chartCanvas = ref(null);
let chartInstance = null;

onMounted(() => {
  // 页面加载时自动获取默认股票的历史数据
  fetchHistoryData();
});

// 监听历史数据变化，更新图表
watch(historyData, async () => {
  if (historyData.value.length > 0) {
    // 使用nextTick确保DOM更新完成后再渲染图表
    await nextTick();
    renderChart();
  }
});

const fetchHistoryData = async () => {
  if (!selectedSymbol.value) {
    error.value = '请输入股票代码';
    return;
  }

  try {
    loading.value = true;
    error.value = null;
    
    const response = await apiService.getStockHistory(selectedSymbol.value, limit.value);
    // 修复：检查响应中是否有error属性来判断是否出错
    if (!response || response.error) {
      error.value = response?.error || '获取历史数据失败';
    } else {
      historyData.value = response.data;
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试';
    console.error('获取历史数据失败:', err);
  } finally {
    loading.value = false;
  }
};

const updateHistoryData = async () => {
  if (!selectedSymbol.value) {
    error.value = '请输入股票代码';
    return;
  }

  try {
    loading.value = true;
    error.value = null;
    
    const response = await apiService.updateStockHistory(selectedSymbol.value);
    // 修复：检查响应中是否有error属性来判断是否出错
    if (!response || response.error) {
      error.value = response?.error || '更新历史数据失败';
    } else {
      alert(`成功更新 ${response.data.count} 条历史数据`);
      // 更新后重新获取数据
      await fetchHistoryData();
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试';
    console.error('更新历史数据失败:', err);
  } finally {
    loading.value = false;
  }
};

const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN');
};

const renderChart = () => {
  // 确保canvas元素存在再尝试渲染图表
  if (!chartCanvas.value) {
    console.warn('Canvas element not found, skipping chart rendering');
    return;
  }

  if (chartInstance) {
    chartInstance.destroy();
  }

  const ctx = chartCanvas.value.getContext('2d');
  
  // 准备图表数据
  const labels = historyData.value.map(item => formatDate(item.date));
  const closingPrices = historyData.value.map(item => item.close);
  
  chartInstance = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [
        {
          label: '收盘价',
          data: closingPrices,
          borderColor: 'rgb(75, 192, 192)',
          backgroundColor: 'rgba(75, 192, 192, 0.2)',
          tension: 0.1,
          fill: true
        }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          beginAtZero: false
        }
      },
      plugins: {
        title: {
          display: true,
          text: `${selectedSymbol.value} 股票价格趋势`
        }
      }
    }
  });
};
</script>

<style scoped>
.stock-history {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.controls {
  display: flex;
  gap: 15px;
  align-items: end;
  margin-bottom: 20px;
  flex-wrap: wrap;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  min-width: 120px;
}

button {
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

button:hover:not(:disabled) {
  background-color: #0056b3;
}

button:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.loading,
.error {
  text-align: center;
  padding: 20px;
}

.error {
  color: #dc3545;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
  margin: 20px 0;
}

.chart-container {
  position: relative;
  height: 500px;
  margin-bottom: 30px;
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
}

.table-wrapper {
  overflow-x: auto;
}

.data-table table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  font-size: 14px;
}

.data-table th,
.data-table td {
  border: 1px solid #dee2e6;
  padding: 12px;
  text-align: left;
}

.data-table th {
  background-color: #e9ecef;
  font-weight: bold;
  color: #495057;
}

.data-table td {
  white-space: nowrap;
}

@media (min-width: 1024px) {
  .controls {
    flex-wrap: nowrap;
  }
  
  .form-group {
    min-width: 150px;
  }
  
  .chart-container {
    height: 600px;
  }
}
</style>